package com.googlecode.allinclusive.fw.core.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZipUtils {

	public static final int BUFFER_SIZE = 1024;
	
	/**
	 * 压缩
	 * @param data
	 * @return
	 */
	public static byte[] compress(byte[] data) {
		ByteArrayInputStream is = null;
		ByteArrayOutputStream os = null;
		GZIPOutputStream gzos = null;
		try {

			is = new ByteArrayInputStream(data);
			os = new ByteArrayOutputStream();
			gzos = new GZIPOutputStream(os);
			int count;
			byte[] compress = new byte[BUFFER_SIZE];
			while ((count = is.read(compress)) != -1) {  
				gzos.write(compress, 0, count);  
			}
			gzos.finish();
			gzos.flush();
			
			byte[] output = os.toByteArray();
			os.flush();
			
			return output;
		} catch (IOException ioe) {
			return null;
		} finally {
			if (gzos != null) { try { gzos.close(); } catch (IOException e) {} }
			if (os != null) { try { os.close(); } catch (IOException e) {} }
			if (is != null) { try { is.close(); } catch (IOException e) {} }
		}
	}
	
	/**
	 * 压缩
	 * @param data
	 * @return
	 */
	public static byte[] uncompress(byte[] data) {
		ByteArrayInputStream is = null;
		GZIPInputStream gzis = null;
		ByteArrayOutputStream os = null;
		try {

			is = new ByteArrayInputStream(data);
			gzis = new GZIPInputStream(is);
			os = new ByteArrayOutputStream();
			int count;
			byte[] compress = new byte[BUFFER_SIZE];
			while ((count = gzis.read(compress)) != -1) {  
				os.write(compress, 0, count);  
			}
			
			byte[] output = os.toByteArray();
			os.flush();
			
			return output;
		} catch (IOException ioe) {
			return null;
		} finally {
			if (gzis != null) { try { gzis.close(); } catch (IOException e) {} }
			if (os != null) { try { os.close(); } catch (IOException e) {} }
			if (is != null) { try { is.close(); } catch (IOException e) {} }
		}
	}
}
